<?php
namespace Admin\Controller;
use Think\Controller;
class GoodsController extends PublicController {

	//商品列表
	public function listAction(){
		$Model=D("Goods"); // 实例化Goods对象		
		
		//分类读取
		$clist=$this->categotyselect();
		$this->assign('clist',$clist);// 赋值数据集

		//品牌读取
		$blist=$this->brandselect();
		$this->assign('blist',$blist);// 赋值数据集
				
		//搜索
		$keyword=I('get.keyword');
		$status=I('get.status',-1,int);
		$catid=I('get.catid',0,int);
		$bid=I('get.bid',0,int);
		$tjian=I('get.tjian',-1,int);
		$frame=I('get.frame',-1,int);
		
		$now=$status;
		$this->assign('now', $now);
		
		if(!empty($keyword)){
			$where['title']  = array('like', '%'.$keyword.'%');
			$map['_complex'] = $where;
		}
		
		if($now == 1){
			$map['status']  = 1;
		}else{	
			$map['status']  = 2;
		}
		
		//分类
		if($catid != 0){
			$list=$this->getchinkid($catid);
			$map['catid']  = array('in',$list);
		}
		
		//品牌
		if($bid != 0){
			$map['bid']  = $bid;
		}
		
		
		if($tjian != -1){
			if($tjian==0){
				$map['new']  = 1;
			}else if($tjian==1){
				$map['hot']  = 1;	
			}else{
				$map['recommend']  = 1;		
			}	
		}
		
		
		if($frame != -1){
			if($frame==0){
				$map['frame']  = 0;	
			}else{
				$map['frame']  = 1;	
			}	
		}	
		
		
		//读取配置文件数据
		$Conf=D("Config"); // 实例化config对象
		$conf_one=$Conf->where(' id=1 ')->find();

		$count      = $Model->where($map)->count();// 查询满足要求的总记录数
		//echo $Model->getlastsql();
		$Page       = new \Think\Page($count,$conf_one['Psize']);// 实例化分页类 传入总记录数和每页显示的记录数		
		$Page->setConfig('prev','上一页');
		$Page->setConfig('next','下一页');
		$Page->setConfig('first','首页');
		$Page->setConfig('last','尾页');		
		$Page->setConfig('header','<li><span class="rows">共 %TOTAL_ROW% 条记录</span></li>');		
		$Page->setConfig('theme','%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');			
		$list = $Model->where($map)->order(' id desc ')->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign('list',$list);// 赋值数据集
		$show       = $Page->show();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
	}
	
	/*
	查找分类下的所有子分类
	*/
	public function getchinkid($id,$array=array()){
		$Model=D("Category"); // 实例化对象			
		$array[]=$id;
		$Tlist=$Model->where(' parentid='.$id)->select();
		foreach($Tlist as $key=>$val){
			$array=$this->getchinkid($val['catid'],$array);
			}
			return $array;
	}
	
	//分类读取
	public function categotyselect(){
		$Role=D("Category"); // 实例化Category对象
		$category=$this->getcateg(0);
		return $category;
	}	
	
	//品牌读取
	public function brandselect(){
		$Brand=D("Brand"); // 实例化role对象
		$brand=$Brand->select();
		return $brand;
	}
	
	//放入回收站
	public function recycleAction(){
		$Model=D("Goods"); // 实例化Goods对象			
		$id=I('get.id');
		$one=$Model->where(' id='.$id)->find();
		if($one){
			$Model->where(' id='.$id)->save(array('status'=>2));	
			$this->success('放入回收站成功', U('goods/list',array('status'=>1)));
		}else{
			$this->success('放入回收站失败', U('goods/list',array('status'=>1)));	
		}
	}
	
	//把回收站的商品还原回商品列表
	public function returnAction(){
		$Model=D("Goods"); // 实例化Goods对象			
		$id=I('get.id');
		$one=$Model->where(' id='.$id)->find();
		if($one){
			$Model->where(' id='.$id)->save(array('status'=>1));	
			$this->success('还原成功', U('goods/list',array('status'=>2)));
		}else{
			$this->success('还原失败', U('goods/list',array('status'=>2)));	
		}
	}	
		
	//商品增加--编辑
	public function saveAction(){
		
		$id=I('get.id',0,int); // 取ID
		//编辑商品属性
		$GAmodel=D("GoodsNAttribute"); // 实例化GoodsNAttribute对象
		$Attrmodel=D("Attribute"); // 实例化Attribute对象

		//关联模型查询
		$ablist=$GAmodel->relation('Attri')->where(' goodsid='.$id)->select();		
		$attrlist=array();
		foreach($ablist as $key=>$val){	
			$attrlist[$val['attid']][]=$val;
		}
		$this->assign('attrlist',$attrlist);// 赋值数据集	
		//print_r($attrlist);
		//die();
		
		//读取商品相册图片
		$Mimages=D("Images"); // 实例化Images对象
		$Ilist=$Mimages->where(" goodsid=$id and type='goods' ")->select();
		$this->assign('Ilist',$Ilist);// 赋值数据集
		
		//分类读取
		$category=$this->categotyselect();
		$this->assign('category',$category);// 赋值数据集

		//品牌读取
		$brand=$this->brandselect();
		$this->assign('brand',$brand);// 赋值数据集
		
		
		
		$Model=D("Goods"); // 实例化对象
		$Model_data=D("GoodsData"); // 实例化对象
		//编辑
		$one=$Model->where(" id=$id ")->find();

		//商品详情读取
		$konw=$Model_data->where(' goodsid='.$id)->find();
		$one['content']=$konw['content'];
        $this->assign('one', $one);
		
		//
		$lang=empty($id)?'增加':'编辑';
		$this->assign('lang', $lang);
		
		$data=I('post.'); 
		
		if(!empty($data)){
			
			//读取配置文件数据
			$Conf=D("Config"); // 实例化config对象
			$conf_one=$Conf->where(' id=1 ')->find();
			
			//上传文件
			if(!empty($_FILES['thumb']['name'])){	
				$finfo=$this->uploadOne('thumb');	
			}
			
			$filesinfo='Public/'.$finfo['savepath'].$finfo['savename'];
			//打水印
			$water='';
			if(!empty($finfo)){
				if($conf_one['watermark'] !=0){
					$water=$this->water($filesinfo,$water_file = $conf_one['waterimage'],$conf_one['watermark']);
					}
				
				}
			
			
			//生成缩略图
			if(!empty($finfo)){
				if($conf_one['thumb'] !=0 && $water!=''){
					$this->thumb($water,$type=$conf_one['thumb'],$width=100,$height=100);
					}
				if($water=='' && $conf_one['thumb'] !=0){
					$this->thumb($filesinfo,$type=$conf_one['thumb'],$width=100,$height=100);
					}
			 	
			}
			
			//验证
			if (!$Model->create()){     // 如果创建失败 表示验证没有通过 输出错误提示信息   
				$this->success($Model->getError(), U('goods/save'));
				die();
			}
			
			if(empty($id)){

				$data['thumb']=$filesinfo;
				$data['addtime']=time();
				
				$insert=$Model->data($data)->add();
				
				//插入商品属性表
				foreach($data['attribute'] as $key=>$values){ 
					 foreach($values as $k=>$v){
						 	$arr=array(
								'attid'=>$key,
								'goodsid'=>$insert,
								'value'=>$v,
								'desc'=>$data['desc'][$key][$k]
							);
						 	$GAmodel->add($arr);
						 } 
				}
				
				//插入详情表
				if($insert){
					$dataD=array(
						'goodsid'=>$insert,
						'content'=>$data['content'],
					);
					$Model_data->data($dataD)->add();
					
					$this->success('增加成功', U('goods/list',array('status'=>1)));
					die();
					}else{
					 $this->error('增加失败',U('goods/list',array('status'=>1)));
					 die();
					}
				}else{
					
					//print_r($data);
					//die();
					
					if(!empty($_FILES['thumb']['name'])){
						$data['thumb']=$filesinfo;	
					}else{
						$data['thumb']=$one['thumb'];	
						}
					$data['addtime']=time();
					$update=$Model->where(" id=$id ")->data($data)->save(); // 根据条件更新记录
					
					//echo $id;
					//print_r($data);
					//die();
					
					if($update){
						
						//商品属性修改
						foreach($data['attribute'] as $key=>$values){ 
							 foreach($values as $k=>$v){
								//判断 	
								if(empty($data['id'][$key][$k])){
									$arradd=array(
										'attid'=>$key,
										'goodsid'=>$id,
										'value'=>$v,
										'desc'=>$data['desc'][$key][$k]
									);
								$GAmodel->data($arradd)->add();
								}else{
									$arr=array(
										'attid'=>$key,
										'value'=>$v,
										'desc'=>$data['desc'][$key][$k]
									);
									$GAmodel->where(' id='.$data['id'][$key][$k])->data($arr)->save();
								}	
							} 
						}
						
						//修改详情表之前，先查询详情表有没有这个商品的详情，没有就ADD，有，SAVE
						$onetow=$Model_data->where('goodsid='.$id)->find();
						if($onetow){
							//详情修改save
							$dataD=array(
								'content'=>$data['content']
							);
							$Model_data->where('goodsid='.$id)->data($dataD)->save();
						}else{
							//详情修改add
							$datac=array(
							    'goodsid'=>$id,
								'content'=>$data['content']
							);
							$Model_data->data($datac)->add();			
						}

							if(!empty($_FILES['thumb']['name'])){
								unlink($one['thumb']);
								$thumb_=dirname($one['thumb']).'/thumb_'.basename($one['thumb']);
								$water_=dirname($one['thumb']).'/water_'.basename($one['thumb']);
								unlink($thumb_);
								unlink($water_);
							}
							$this->success('编辑成功', U('goods/list',array('status'=>1)));
							die();
						}else{
							$this->error('编辑失败',U('goods/list',array('status'=>1)));
							die();
							}
					
					}
			}
			$this->display();
		}
		
	
	//商品相册图片上传
	public function uploadifyAction(){
		$goodsid=I('get.goodsid',0,int);
		$Model=D("Images"); // 实例化Images对象
		$verifyToken = md5('unique_salt' . $_POST['timestamp']);		
		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
			 $finfo=$this->uploadOne('Filedata');	
			 $filesinfo='Public/'.$finfo['savepath'].$finfo['savename'];
			 $data=array(
			 	'type'=>'goods',
				'url'=>$filesinfo,
				'sort'=>1,
				'status'=>1,
				'goodsid'=>$goodsid,
			 
			 );
			 $id1=$Model->data($data)->add();
			 $arry=array(
			 	'path'=>$filesinfo,
				'sort'=>1,
				'id'=>$id1
			 );
			 echo json_encode($arry);
			} else {
				echo '上传失败';
		}
		
	}
	
	
	//商品属性ajax
	public function attributeAction(){
		
		$Model=D("Attribute"); // 实例化对象
		
		$catid=I('post.catid',0,int);
		
		$Acatid=$this->gettopcatid($catid);
		
		$Alist=$Model->where(' catid='.$Acatid)->select();
		
		echo json_encode($Alist);
		
		}
		
	
	//查找分类的最顶级的id
	public function gettopcatid($catid){
		$Model=D("Category"); // 实例化Category对象
		$oneid=$Model->where(' catid='.$catid)->find();
		if($oneid['parentid']==0){
			return $catid;
			}else{
				return $this->gettopcatid($oneid['parentid']);
			}
	}	
		
		
	//商品删除
	public function delAction(){
		$Model=D("Goods"); // 实例化Goods对象
		$GAmodel=D("GoodsNAttribute"); //实例化GoodsNAttribute对象
		$Model_data=D("GoodsData"); // 实例化GoodsData对象
		$Mimages=D("Images"); // 实例化GoodsData对象
		$id=I('get.id'); // 取ID
		$one=$Model->where(' id='.$id)->find();
		if(!empty($one)){
			if(file_exists($one['url'])){
				unlink($one['url']);
				}
			$del=$Model->where(" id=$id ")->delete(); // 删除id为什么的用户数据	
			if($del){
				
				//删除商品属性表
				$GAmodel->where(" goodsid=$id ")->delete();
				
				//删除属性表
				$Model_data->where(" goodsid=$id ")->delete();
				
				//删除相册表
				$Imlist=$Mimages->where(" goodsid=$id and type='goods' ")->select();
				foreach($Imlist as $key=>$val){
					if(file_exists($val['url'])){
						unlink($val['url']);
					}
				}
				$Mimages->where(" goodsid=$id and type='goods' ")->delete();
				
				$this->success('删除成功', U('goods/list',array('status'=>2)));
				die();
				}else{
				$this->error('删除失败', U('goods/list',array('status'=>2)));
				die();
				}
			
		}	
	}
	
	//批量操作
	public function batchdelAction(){

		$Model=D("Goods"); // 实例化admin对象
		$GAmodel=D("GoodsNAttribute"); //实例化GoodsNAttribute对象
		$Model_data=D("GoodsData"); // 实例化GoodsData对象
		/*批量删除*/
		$batch=I('post.del');
		if(!empty($batch)){
			$id=I('post.id');
			foreach($id as $key=>$val){	
				$Model->where(" id=$val ")->delete(); // 删除id为什么的用户数据	
				$GAmodel->where(" goodsid=$id ")->delete();
				$Model_data->where(" goodsid=$id ")->delete();	
				}
		}
		
		/*批量上架*/
		$batch=I('post.status1');
		if(!empty($batch)){	
			$id=I('post.id');
			foreach($id as $key=>$val){		
				$Model->where(" id=$val ")->save($data=array('frame'=>1)); // 根据条件更新记录
				}
		}
		
		/*批量下架*/
		$batch=I('post.status0');
		if(!empty($batch)){	
			$id=I('post.id');
			foreach($id as $key=>$val){
				$Model->where(" id=$val ")->save($data=array('frame'=>0)); // 根据条件更新记录
				}
		}
		
		$this->success('操作成功', U('goods/list',array('status'=>1)));
		
	}
	
	//点击改变 new hot recommend 状态
	public function clickajaxAction(){
		$Model=D("Goods"); // 实例化对象
		$statusid=I('post.statusid',0,int);
		$id=I('post.id',0,int);
		$type=I('post.type');
			
		$one=$Model->where(' id='.$id)->find();
		if($one){
			if($type=='new'){
				if($statusid){
					$Model->where(" id=".$id)->save($data=array('new'=>0)); // 根据条件更新记录
					echo 1;
				}else{
					$Model->where(" id=".$id)->save($data=array('new'=>1)); // 根据条件更新记录
					echo 1;
				}
			}else if($type=='hot'){
				
				if($statusid){
					$Model->where(" id=".$id)->save($data=array('hot'=>0)); // 根据条件更新记录
					echo 1;
				}else{
					$Model->where(" id=".$id)->save($data=array('hot'=>1)); // 根据条件更新记录
					echo 1;
				}
				
			}else if($type=='recommend'){
				if($statusid){
					$Model->where(" id=".$id)->save($data=array('recommend'=>0)); // 根据条件更新记录
					echo 1;
				}else{
					$Model->where(" id=".$id)->save($data=array('recommend'=>1)); // 根据条件更新记录
					echo 1;
				}
			}else{
				if($statusid){
					$Model->where(" id=".$id)->save($data=array('frame'=>0)); // 根据条件更新记录
					echo 1;
				}else{
					$Model->where(" id=".$id)->save($data=array('frame'=>1)); // 根据条件更新记录
					echo 1;
				}
			}
		}else{	
			echo 0;
		}		
	}	
	
	
	//快捷修改
	public function shortcutajaxAction(){
		
		$Model=D("Goods"); // 实例化对象
		$sort=I('post.sort1');
		$id=I('post.id',0,int);
		$type=I('post.type');
			
		$one=$Model->where(' id='.$id)->find();
		
		if($one){
			if($type=='sort'){
				$Model->where(" id=".$id)->save($data=array('sort'=>$sort)); // 根据条件更新记录
				echo 1;
			}	
		}else{
			echo 0;
		}
		
	}
	
	
	//图片修改处理ajax
	public function imageajaxAction(){
		$Model=D("Images"); // 实例化对象
		$sort=I('post.sort');
		$id=I('post.id');
		$type=I('post.type');
		
		//修改图片排序
		if($type=='sort'){
			$eid=$Model->where('id='.$id)->find();
			if($eid){
					$Model->where('id='.$id)->data(array('sort'=>$sort))->save();
					echo 1;
				}else{
					echo 0;
			}
		}
		
		//删除图片
		if($type=='delimages'){
			$eid=$Model->where('id='.$id)->find();
			if($eid){
					$Model->where('id='.$id)->delete();
					unlink($eid['url']);
					echo 1;	
				}else{
					echo 0;
			}
			
		}
		
		//删除商品属性attriddel
		$GAmodel=D("GoodsNAttribute"); // 实例化GoodsNAttribute对象
		if($type=='attriddel'){
			$eid=$GAmodel->where('id='.$id)->find();
			if($eid){
					$GAmodel->where('id='.$id)->delete();
					echo 1;	
				}else{
					echo 0;
			}
			
		}
	}

		//读取分类树-------------------------------
	public function getcateg($pid,$retul=array(),$k=0){
		$Model=D("Category"); // 实例化对象
		
		
		$list=$Model->where(' parentid='.$pid)->select();
		
		
		foreach($list as $key=>$val){
			
			$chin=$this->getchin($val['catid']);
			if(empty($chin)){
					$chh=0;
				}else{
					$chh=1;
				}
			$val['chh']=$chh;
			
			$str='';
			for($i=0;$i<$k;$i++){
				$str.='|-';
				}
			$val['name']=$str.$val['name'];
					
			$retul[]=$val;	
			$retul=$this->getcateg($val['catid'],$retul,$k+1);
			
		}
		 return $retul;
	}
	
	
	public function getchin($pid){
		$Model=D("Category"); // 实例化对象		
		return $row=$Model->where(' parentid='.$pid)->find();
	}	

	
}